package com.liuwang.meal.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketUtil {
	private static Socket socket;

	public SocketUtil(String ip, int port) throws UnknownHostException, IOException {
		// 创建Socket
		socket = new Socket(ip, port);
	}

	// 发送消息
	public String sendMsg(String message) throws IOException {
		PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
		InputStream in = socket.getInputStream();

		// 向服务器发送消息
		out.println(message + "\r\n");
		out.flush();// /

		// 接收来自服务器的消息
		StringBuffer strbuf = new StringBuffer();
		byte[] buf = new byte[1024];
		int len = -1;
		int count = 0;
		while ((len = in.read(buf)) != -1) {
			String line = new String(buf, 0, len, "UTF-8");
			strbuf.append(line);
			count = count + line.length();
			if (count >= Integer.parseInt((line.split(",")[0].substring(26)))) {
				break;
			}
		}

		return strbuf.toString();
	}

	// 关闭
	public void closeSocket() {
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}